<?php

/**
 * 推送-历史记录： 
 *
 * @author mengyu wang
 */

require_once 'CommonController.php';

class Admin_PushHistoryController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_PushTask();
        $this->_userModel = new Application_Model_User();
        $this->_psbModel = new Application_Model_PushSequenceBk();
        $this->view->title = "管理中心";
    } 
    
    /**
     * 总入口
     */
    public function pushListAction()
    {
        $this->view->key = $day = $this->_request->get('day');
        if ($day == '' || $day == 'today') {
            //默认为今天
            $this->opReportToday();
        } else if ($day == 'yestoday') {
            $this->opReportYestoday();
        } else if ($day == 'last-seven-day') {
            $this->opReportLastSevenDay();
        } else if ($day == 'last-thirty-day') {
            $this->opReportLastThirtyDay();            
        } else if ($day == 'last-three-month') {
            $this->opReportLastThreeMonth();
        } else if($day == 'all') {
            $this->opReportAll();
        } else if ($day == 'between') {
            $this->opReportBetween();
        }
        $this->renderScript('push-task/push-history.php');
    }
    /**
     * 推送箱-(时间范围)
     * @param string $startTime
     * @param string $endTime
     * @param int $type
     */
    public function rangeMember($startTime, $endTime, $type = 1)
    {
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();

        $this->view->title = '推送箱';
        $this->view->reportType = 'push-list';
        $this->view->versions = $this->_model->getVersion($productCode, $startTime, $endTime, 3);
        $this->view->osNames = $this->_model->getOs($productCode, $startTime, $endTime, 3);
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();

        //获取当前页码
        $pageSize = 10;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['productCode'] = $productCode;
        $vars['startTime'] = $startTime ? $startTime : trim($this->_request->get('startTime'));
        $vars['endTime'] = $endTime ? $endTime : trim($this->_request->get('endTime'));
        $vars['osName'] = trim($this->_request->get('osName'));
        $vars['version'] = trim($this->_request->get('version'));
        $vars['keyword'] = trim($this->_request->get('keyword'));
        $vars['day'] = trim($this->_request->get('day'));
        
        $urls = $vars;

        if ($vars['productCode'] != '') {
            $wheres[] = "`pp`.`productCode` = '{$vars['productCode']}'";
        }
        if ($vars['startTime'] != '' ) {
            $wheres[] = "`pp`.`endTime` >= '" . addslashes($vars['startTime'].' 0:0:0') . "'";
        }
        if ($vars['endTime'] != '') {
            $wheres[] = "`pp`.`endTime` <= '" . addslashes($vars['endTime'].' 23:59:59') . "'";
        }
        if ($vars['osName'] != '') {
             $wheres[] = "`pp`.`osName` like '%" . addslashes($vars['osName']) . "%'";
        }
        if ($vars['version'] != '') {
            $wheres[] = "`pp`.`version` like '%" . addslashes($vars['version']) . "%'";
        }
        if ($vars['keyword'] != '') {
            $wheres[] = "`pp`.`msgInfo` like '%" . addslashes($vars['keyword']) . "%'";
        }
        //筛选出草稿箱的
        $wheres[] = "`pp`.`status` = 3";
        
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "
            SELECT `pp`.*, `u`.`name` AS `name`,`pp`.msgInfo,`pp`.startTime, `pp`.osName
            FROM `{$this->_model->getTableName()}` AS `pp` 
            LEFT JOIN `{$this->_userModel ->getTableName()}` AS `u` ON `u`.`userName` = `pp`.`addUser`
            {$where} 
            ORDER BY `pp`.`addTime` DESC
        ";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();
        
        
        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        $rows = $dbPaginator->getRows();
        //完成度统计
        $res = $this->_model->getFinished($rows);

        //分配view(分页处理后的记录集以及分页HTML字符)
        
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $res;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
    }
    
    /**
     * 昨天
     * Enter description here ...
     * @param int type
     */
    public function opReportYestoday($type = 1)
    {
        $this->view->key = 'yestoday';
        $startTime = date('Y-m-d',strtotime("-1 day"));
        $this->rangeMember($startTime,$startTime,$type);    
    }    
     /**
     * 今天
     * Enter description here ...
     * @param int type
     */
    public function opReportToday($type = 1)
    {
        $this->view->key = 'today';
        $startTime = date('Y-m-d',strtotime("now"));
        $this->rangeMember($startTime,$startTime,$type);    
    }
    
    /**
     * 最近七天
     * Enter description here ...
     * @param int type
     */
    public function opReportLastSevenDay($type = 1)
    {
        $this->view->key = 'last-seven-day';
        $startTime = date('Y-m-d',strtotime("-8 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->rangeMember($startTime, $endTime, $type);
    }
    
    /**
     * 最近30天
     * Enter description here ...
     * @param int type
     */
    public function opReportLastThirtyDay($type = 1)
    {
        $this->view->key = 'last-thirty-day';
        $startTime = date('Y-m-d',strtotime("-31 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->rangeMember($startTime, $endTime, $type);
    }
    
    /**
     * 最近3个月
     * Enter description here ...
     * @param int type
     */
    public function opReportLastThreeMonth($type = 1)
    {
        $this->view->key = 'last-three-month';
        $startTime = date('Y-m-d',strtotime("-3 months"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->rangeMember($startTime, $endTime,$type);
    }
    
    /**
     * 选择时间段
     * Enter description here ...
     * @param int type
     */
    public function opReportBetween($type = 1)
    {
        $this->view->key = 'between';
        $this->view->title = '推送历史记录';
        $this->view->reportType = 'push-list';
        if ($this->_request->isPost() || 1) {
            $startTime = $this->_request->get('startTime');
            $endTime = $this->_request->get('endTime');
            $backUrl = $this->view->projectUrl(array('action' => 'push-list','day'=>'between','startTime'=>$startTime,'endTime'=>$endTime));
            if (!$startTime || !$endTime) {
                 echo $this->view->message('请选择时间范围！',$backUrl); exit;
            } else if($startTime>$endTime) {
                 echo $this->view->message('开始时间必须早于结束时间，请重新填写！', $backUrl); exit;  
            } else {
                $this->view->startTime = $startTime;
                $this->view->endTime = $endTime;
                @$this->view->vars['startTime'] = $this->view->startTime;
                @$this->view->vars['endTime'] = $this->view->startTime;
                
            }
            if ($startTime == $endTime) {
                $this->rangeMember($startTime, $startTime, $type);
            } else {
                $this->rangeMember($startTime, $endTime, $type);
            }
        }
    }
    
    
  /**
  * 下载EXCEL
  */
    public function exportPushAction()
    {
    	//收集数据
        $filter = new Zend_Filter_StripTags();
        $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
        $endTime = $filter->filter(trim($this->_request->getPost('endTime')));              
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $osName = $filter->filter(trim($this->_request->getPost('osName')));  
        $version = $filter->filter(trim($this->_request->getPost('version'))); 
        $keyword = $filter->filter(trim($this->_request->getPost('keyword'))); 
        $status = 3;
        if ($startTime && $endTime) {
        	if ($startTime != $endTime) {
        		$timeMessage = $startTime . '_' . $endTime;
        	} else {
        		$timeMessage = $startTime;
        	}
        } else {
        	$timeMessage = 'all_';
        }
        
        $rows = $this->_model->getExportHistoryData($startTime, $endTime, $productCode,$osName,$version,$keyword,$status);

        
        //将数据导出到EXCEL文件
        $pModel = new Application_Model_PartnerProduct();
        $product = $pModel->fetchRow("code = '{$productCode}'");
        $keyOsArr = array('推送者',	'推送信息',	'推送结束日期',	'推送平台');
        $itemArr = array('name', 'msgInfo', 'endTime', 'osName');
        $adPaidFile = $this->_model->writeToExcel('push_history', $timeMessage, $rows,$productCode,$keyOsArr,'PUSH消息记录');
        $path = PUBLIC_PATH . "/data/pushTask/";
        $filename = $path . $adPaidFile;
        
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $adPaidFile);
		readfile($filename);
        
        //文件的删除
        @unlink($filename);
        exit();
    }
    
    /**
     * 删除产品
     * 
     * @return void
     */
    public function deleteAction(){
        $backUrl = trim($this->_request->get('backUrl'));//返回的url
        
        if ($this->_request->isPost()) {
            $groupIdArr = $this->_request->get('selectId');
            if (!empty($groupIdArr)) {
                foreach ($groupIdArr as $id) {
                    $row = $this->_model->fetchRow("`id` = {$id}");
                    if (!empty($row)) {
                        $res = $this->_model->delete("`id` = {$id}");
                        if(!$res){
                            exit($this->view->message('删除失败！',  $backUrl));
                        }
                    } else {
                        exit($this->view->message('数据不存在！',  $backUrl));
                    }
                }
            }
        }
        
        exit($this->view->message('删除成功！', $backUrl));
        
    }
   
}

